import shop from '../../api/shop'
import { PRODUCTS } from '../mutation-types'

// 初始化state
const state = {
    all: []
}

const getters = {}

const actions = {
    getAllProducts({ commit }) { // 这种写法是js的参数展开，store.commit
        shop.getProducts(products => {
            commit(PRODUCTS.SET_PRODUCTS, products) // 将shop.js内所有产品加入all
        })
    }
}

const mutations = {
    // 初始化库存为products
    [PRODUCTS.SET_PRODUCTS](state, products) { // 首个参数总是state，引用的是本地state
        state.all = products
    },
    [PRODUCTS.DECREMENT_PRODUCT_INVENTORY](state, { id }) {
        const product = state.all.find(product => product.id == id)
        product.inventory--
    }
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}